package com.lhh.company.website.admin;

import com.lhh.company.website.config.SysUserDetails;
import com.lhh.company.website.entity.Res;
import com.lhh.company.website.entity.SysFile;
import com.lhh.company.website.service.SysFileService;

import com.lhh.company.website.utils.SysUtils;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@Log4j2
public class FileApi {

    @Resource
    SysFileService sysFileService;

    @RequestMapping("/file/upload")
    public Res upload(MultipartFile file, String fileName, @AuthenticationPrincipal SysUserDetails userDetails) throws Exception {

        String fileId = SysUtils.getId();
        try {
            sysFileService.fileUpload(fileId ,file,fileName,userDetails);
            return Res.succ(fileId,"文件上传成功");
        } catch (IOException e) {
            log.error(e);
            try {
                sysFileService.delete(fileId);
            }catch (IOException e1) {
                log.error(e1);
            }
            return Res.fail("文件上传失败");
        }

    }

    @RequestMapping("/file/tmp/upload")
    public Res uploadTmp(MultipartFile file,String fileName) throws Exception {

        String fileId = SysUtils.getId();
        try {
            SysFile sysFile = sysFileService.fileUploadToTmp(fileId ,file,fileName);
            return Res.succ(sysFile,"文件上传成功");
        } catch (IOException e) {
            log.error(e);
            try {
                sysFileService.delete(fileId);
            }catch (IOException e1) {
                log.error(e1);
            }
            return Res.fail("文件上传失败");
        }

    }

    @RequestMapping("/file/delete")
    @Transactional(rollbackFor = Exception.class)
    public Res delete(String id) {
        try {
            return Res.succ("删除成功");
        } catch (Exception e) {
            log.error(e);
            return Res.fail("删除失败");
        }

    }

}
